const { merge } = require('webpack-merge')
const common = require('./webpack.common')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')
// webpack 5.x 匹配terser-webpack-plugin 5.x
// webpack 4.x 匹配terser-webpack-plugin 4.x
const TerserWebpackPlugin = require('terser-webpack-plugin')

// merge不好使，先删除掉，再合并
common.module.rules.splice(0, 2)

module.exports = merge(common, {
  mode: 'production',
  optimization: {
    splitChunks: {
      chunks: 'all'
    },
    // 开启压缩,minimizer才会生效，或者 mode production 也会默认开启minimize
    minimize: true,
    // 如果配置了minimizer，就是默认自定义压缩器，需要手动加回来
    minimizer: [
      // 没有这个的话，mode production 模式下js不压缩，手动加回来，这是内置的js压缩插件
      new TerserWebpackPlugin(),
      // 压缩css
      new OptimizeCssAssetsWebpackPlugin()
    ],
    // 模块只导出被使用的成员
    usedExports: true
  },
  module: {
    rules: [
      {
        test: /\.(le|c)ss$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader'],
        exclude: /node_modules/
      },
      {
        test: /\.(png|svg|jpg|jpeg|bmp)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              esModule: false,
              limit: 10 * 1024,
              name: 'img/[name].[ext]'
            }
          },
          {
            // 开启图片压缩
            loader: 'image-webpack-loader',
            options: {
              mozjpeg: {
                progressive: true
              },
              // optipng.enabled: false will disable optipng
              optipng: {
                enabled: false
              },
              pngquant: {
                quality: [0.65, 0.90],
                speed: 4
              },
              gifsicle: {
                interlaced: false
              },
              // the webp option will enable WEBP
              webp: {
                quality: 75
              }
            }
          }
        ]
      }
    ]
  },
  plugins: [
    // 默认删除output.path
    new CleanWebpackPlugin(),
    // 提取css成单独文件
    new MiniCssExtractPlugin({
      filename: 'css/[name].[chunkhash:5].css'
    }),
    new CopyWebpackPlugin(
      {
        patterns: [
          {
            from: 'public/*.ico',
            to: '.'
          }
        ]
      }
    )
  ]
})
